/*
 *  Copyright 2019-2023 oyun
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.oyun.modules.medicine.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.oyun.config.FileProperties;
import com.oyun.modules.medicine.domain.*;
import com.oyun.modules.medicine.domain.vo.DoctorQueryCriteria;
import com.oyun.modules.medicine.mapper.AdministrativeOfficeMapper;
import com.oyun.modules.medicine.mapper.DoctorMapper;
import com.oyun.modules.medicine.mapper.DoctorPictureMapper;
import com.oyun.modules.medicine.service.DoctorService;
import com.oyun.segment.convert.itmd.IntermediateCodeUtils;
import com.oyun.utils.FileUtil;
import com.oyun.utils.PageResult;
import com.oyun.utils.PageUtil;
import com.oyun.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author aoyun
 * @description 服务实现
 * @date 2024-04-28
 **/
@Service
@RequiredArgsConstructor
public class DoctorServiceImpl extends ServiceImpl<DoctorMapper, Doctor> implements DoctorService {

    private final DoctorMapper doctorMapper;

    private final DoctorPictureMapper doctorPictureMapper;

    private final AdministrativeOfficeMapper administrativeOfficeMapper;

    private final FileProperties properties;

    @Override
    public PageResult<Doctor> queryAll(DoctorQueryCriteria criteria, Page<Object> page) {
        if (StringUtils.isNotEmpty(criteria.getName())) {
            criteria.setReplaceAll(IntermediateCodeUtils.mn2Code(criteria.getName()).replaceAll("-", " -"));
        }
        IPage<Doctor> all = doctorMapper.findAll(criteria, page);
        Acquire(all.getRecords());
        return PageUtil.toPage(all);
    }

    @Override
    public List<Doctor> queryAll(DoctorQueryCriteria criteria) {
        return doctorMapper.findAll(criteria);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(Doctor resources) {
        convertCode(resources);
        save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Doctor resources) {
        Doctor doctor = getById(resources.getId());
        doctor.copy(resources);
        convertCode(doctor);
        saveOrUpdate(doctor);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(List<Long> ids) {
        removeBatchByIds(ids);
        LambdaQueryWrapper<DoctorPicture> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(DoctorPicture::getDoctorId, ids).eq(DoctorPicture::getStatus, 1);
        List<DoctorPicture> doctorPictures = doctorPictureMapper.selectList(wrapper);
        for (DoctorPicture doctorPicture : doctorPictures) {
            doctorPicture.setStatus(0);
            doctorPictureMapper.updateById(doctorPicture);
        }
    }

    @Override
    public void download(List<Doctor> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (Doctor doctor : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("科室id", doctor.getAdministrativeId());
            map.put("出生日期", doctor.getBirthday());
            map.put("从医时间", doctor.getMedicalTime());
            map.put("性别", doctor.getSex());
            map.put("毕业学校", doctor.getSchool());
            map.put("学历(字典)", doctor.getEducationalBackground());
            map.put("职称(字典)", doctor.getNickname());
            map.put("专家(字典)", doctor.getExpert());
            map.put("姓名", doctor.getMnName());
            map.put(" mnNameCode", doctor.getMnNameCode());
            map.put(" zhName", doctor.getZhName());
            map.put("蒙语介绍", doctor.getMnIntroduce());
            map.put(" mnIntroduceCode", doctor.getMnIntroduceCode());
            map.put(" zhIntroduce", doctor.getZhIntroduce());
            map.put(" createBy", doctor.getCreateBy());
            map.put(" createTime", doctor.getCreateTime());
            map.put(" updateBy", doctor.getUpdateBy());
            map.put(" updateTime", doctor.getUpdateTime());
            map.put("备注", doctor.getRemark());
            map.put(" status", doctor.getStatus());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public String uploadOrUpdate(MultipartFile file, HttpServletRequest request, Long id) {
        File filee = new File(properties.getPath().getPath() + "/doctor");
        if (!filee.exists()) {//不存在
            filee.mkdirs();
        }
        String filename = file.getOriginalFilename();//获取文件名称带后缀名
        String uid = UUID.randomUUID().toString();//生成32为uuid值
        String suffix = filename.substring(filename.lastIndexOf(".")); //切割获取.后面的jpg
        String newFile = uid + suffix;//拼接新的文件名称
        File file1 = new File(filee + "/" + newFile);
        try {
            file.transferTo(file1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        LambdaQueryWrapper<DoctorPicture> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(id != null, DoctorPicture::getDoctorId, id).eq(DoctorPicture::getStatus, 1);
        DoctorPicture picture = doctorPictureMapper.selectOne(wrapper);
        if (picture == null) {
            //新增
            DoctorPicture doctorPicture = new DoctorPicture();
            doctorPicture.setDoctorId(id);
            doctorPicture.setPathImage("/doctor/" + newFile);
            doctorPicture.setStatus(1);
            doctorPictureMapper.insert(doctorPicture);
        } else {
            //修改
            picture.setPathImage("/doctor/" + newFile);
            picture.setStatus(1);
            doctorPictureMapper.updateById(picture);
        }
        return newFile;
    }

    @Override
    public Object getByName(String name) {
        String replaceAll = IntermediateCodeUtils.mn2Code(name).replaceAll("-", " -");
        LambdaQueryWrapper<Doctor> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.like(Doctor::getZhName, name).or().like(Doctor::getMnNameCode, replaceAll);
        List<Doctor> doctors = doctorMapper.selectList(wrapper1);
        Acquire(doctors);
        return doctors;
    }

    @Override
    public Object getDoctorByOfficeId(Long officeId, Long pageNum, Long pageSize) {
        Page<Doctor> objectPage = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Doctor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Doctor::getAdministrativeId, officeId);
        Page<Doctor> doctorPage = doctorMapper.selectPage(objectPage, wrapper);
        Acquire(doctorPage.getRecords());
        return doctorPage;
    }


    private void convertCode(Doctor doctor) {
        doctor.setMnNameCode(IntermediateCodeUtils.mn2Code(doctor.getMnName()).replaceAll("-", " -"));
        doctor.setMnIntroduceCode(IntermediateCodeUtils.mn2Code(doctor.getMnIntroduce()).replaceAll("-", " -"));
    }

    private void Acquire(List<Doctor> list) {
        for (Doctor doctor : list) {
            LambdaQueryWrapper<DoctorPicture> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(doctor.getId() != null, DoctorPicture::getDoctorId, doctor.getId());
            DoctorPicture doctorPicture = doctorPictureMapper.selectOne(wrapper);
            if (doctorPicture != null) doctor.setImage(doctorPicture.getPathImage());

            LambdaQueryWrapper<AdministrativeOffice> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(AdministrativeOffice::getId, doctor.getAdministrativeId());
            AdministrativeOffice administrativeOffice = administrativeOfficeMapper.selectOne(wrapper1);
            if (administrativeOffice != null) doctor.setAdministrativeName(administrativeOffice.getMnName());
        }
    }
}
